import { FullConfig } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';

async function globalTeardown(config: FullConfig) {
  console.log('🧹 开始全局清理...');

  try {
    // 清理测试数据目录
    const testResultsDir = path.join(process.cwd(), 'test-results');
    if (fs.existsSync(testResultsDir)) {
      console.log('📁 清理测试结果目录...');
      // 保留最新的测试结果，清理旧的
      const files = fs.readdirSync(testResultsDir);
      const now = Date.now();
      const oneDayAgo = now - 24 * 60 * 60 * 1000;

      files.forEach(file => {
        const filePath = path.join(testResultsDir, file);
        const stats = fs.statSync(filePath);

        if (stats.isFile() && stats.mtime.getTime() < oneDayAgo) {
          fs.unlinkSync(filePath);
          console.log(`🗑️  删除旧文件: ${file}`);
        }
      });
    }

    // 清理截图目录
    const screenshotsDir = path.join(process.cwd(), 'screenshots');
    if (fs.existsSync(screenshotsDir)) {
      console.log('📸 清理截图目录...');
      const files = fs.readdirSync(screenshotsDir);
      files.forEach(file => {
        const filePath = path.join(screenshotsDir, file);
        if (fs.statSync(filePath).isFile()) {
          fs.unlinkSync(filePath);
          console.log(`🗑️  删除截图: ${file}`);
        }
      });
    }

    // 清理视频目录
    const videosDir = path.join(process.cwd(), 'videos');
    if (fs.existsSync(videosDir)) {
      console.log('🎥 清理视频目录...');
      const files = fs.readdirSync(videosDir);
      files.forEach(file => {
        const filePath = path.join(videosDir, file);
        if (fs.statSync(filePath).isFile()) {
          fs.unlinkSync(filePath);
          console.log(`🗑️  删除视频: ${file}`);
        }
      });
    }

    // 生成测试摘要报告
    console.log('📊 生成测试摘要报告...');
    const summary = {
      testDate: new Date().toISOString(),
      environment: process.env.NODE_ENV || 'test',
      baseUrl: process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:3001',
      apiUrl: process.env.REACT_APP_API_URL || 'http://localhost:6001',
      cleanup: {
        testResultsDir: fs.existsSync(testResultsDir) ? 'cleaned' : 'not exists',
        screenshotsDir: fs.existsSync(screenshotsDir) ? 'cleaned' : 'not exists',
        videosDir: fs.existsSync(videosDir) ? 'cleaned' : 'not exists'
      }
    };

    const summaryPath = path.join(process.cwd(), 'test-summary.json');
    fs.writeFileSync(summaryPath, JSON.stringify(summary, null, 2));
    console.log(`📄 测试摘要已保存: ${summaryPath}`);

  } catch (error) {
    console.error('❌ 全局清理失败:', error);
    // 不抛出错误，避免影响测试结果
  }

  console.log('✅ 全局清理完成');
}

export default globalTeardown;